package com.juyu.reader.author.controller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.juyu.reader.author.common.PageDirective;
import com.juyu.reader.author.model.Author;
import com.juyu.reader.author.model.Book;
import com.juyu.reader.author.model.BookChapter;
import com.juyu.reader.author.model.Page;
import com.juyu.reader.author.service.BookChapterService;
import com.juyu.reader.author.service.BookService;
import com.juyu.reader.author.util.BigDecimalUtil;
import com.juyu.reader.author.util.StringUtil;

@Controller
@RequestMapping("/chapter")
public class BookChapterController extends BaseController {
	@Autowired
	private BookChapterService bookChapterService;
	@Autowired
	private BookService bookService;

	@RequestMapping("/add")
	public ModelAndView chapterAdd(HttpServletRequest request, HttpServletResponse response, Book book, Page page) {
		Author sessionAuthor = this.getSessionAuthor(request);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookId(book.getBookId());
		findBook.setBookFlag(-1);
		List<Book> bookList = bookService.findBook(findBook);
		attrMap.put("bookId", book.getBookId());
		if (bookList.size() == 1) {
			attrMap.put("book", bookList.get(0));
		} else {
			return this.packModeAndView(request, "/error", "该书籍不存在！", attrMap);
		}
		// 查询章节排序
		int chapterSeq = 1;
		int bLastSeq = bookList.get(0).getBookLastSeq();
		int cLastSeq = 0;
		List<BookChapter> lastChapterList = bookChapterService.findBookChapterLastSeq(book.getBookId());
		if (lastChapterList.size() >= 1) {
			if (lastChapterList.get(0).getChapterSeq() > 0) {
				cLastSeq = lastChapterList.get(0).getChapterSeq() + 1;
			}
		}
		if (bLastSeq >= cLastSeq) {
			chapterSeq = bLastSeq;
		} else {
			chapterSeq = cLastSeq;
		}
		if (chapterSeq <= 0) {
			chapterSeq = 1;
		}
		attrMap.put("chapterSeq", chapterSeq);
		return this.packModeAndView(request, "/chapterAdd", null, attrMap);
	}

	@RequestMapping("/draftList")
	public ModelAndView draftList(HttpServletRequest request, HttpServletResponse response, Book book, Page page) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		BookChapter findBookChapter = new BookChapter();
		findBookChapter.setBookId(book.getBookId());
		findBookChapter.setChapterStatus(3);// 0默认，1通过，-1拒绝，2审核中，3待发布（草稿箱）
		findBookChapter.setLimit(page.getLimit());
		findBookChapter.setPageNo(page.getPageNo());
		List<BookChapter> bookChapterList = bookChapterService.findBookChapter(findBookChapter);
		int count = bookChapterService.countBookChapter(findBookChapter);
		attrMap.put("bookChapterList", bookChapterList);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request));
		attrMap.put("bookId", book.getBookId());
		return this.packModeAndView(request, "/draftList", null, attrMap);
	}

	@RequestMapping("/publishList")
	public ModelAndView publishList(HttpServletRequest request, HttpServletResponse response, Book book, Page page) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		BookChapter findBookChapter = new BookChapter();
		findBookChapter.setBookId(book.getBookId());
		findBookChapter.setLimit(page.getLimit());
		findBookChapter.setPageNo(page.getPageNo());
		List<BookChapter> bookChapterList = bookChapterService.findBookChapterPublish(findBookChapter);
		int count = bookChapterService.countBookChapterPublish(findBookChapter);
		// 设置章节是否允许编辑
		for (BookChapter bc : bookChapterList) {
			if (bc.getChapterPublishDate() == null) {
			} else {
				Calendar calendar = Calendar.getInstance();
				long t = (calendar.getTime().getTime() / 1000) - (bc.getChapterPublishDate().getTime() / 1000);
				if (t < 60 * 60 * 24) {
					bc.setIsEnableEdit(1);
				}
			}
		}
		attrMap.put("bookChapterList", bookChapterList);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request));
		attrMap.put("bookId", book.getBookId());
		return this.packModeAndView(request, "/publishList", null, attrMap);
	}

	@RequestMapping("/save")
	public String chapterSave(HttpServletRequest request, BookChapter bookChapter, Model model) {
		Author sessionAuthor = this.getSessionAuthor(request);
		String chapterContent = request.getParameter("content1");
		chapterContent = this.resetContent("<p>" + chapterContent);
		int count = this.valiContent(chapterContent);
		if (count < 3) {
			return this.packStringView(request, "/error", "章节排版存在错误，请注意排版，头文字不用缩进，段落要回车换行。如有问题请点击查看使用帮助或联系QQ客服！",
					model);
		}
		bookChapter.setChapterContent(chapterContent);
		bookChapter.setChapterStatus(3);
		// 如果是付费，则计算价格
		if (bookChapter.getChapterFree() == 2) {
			double chapterAmount = BigDecimalUtil.mul(BigDecimalUtil.div(bookChapter.getChapterWords(), 1000, 2), 0.05);
			chapterAmount = BigDecimalUtil.round(chapterAmount, 2);
			bookChapter.setChapterAmount(chapterAmount);
		}
		bookChapterService.insertBookChapter(bookChapter);
		Book updateBook = new Book();
		updateBook.setAuthorId(sessionAuthor.getAuthorId());
		updateBook.setBookId(bookChapter.getBookId());
		updateBook.setBookWords(bookChapter.getChapterWords());
		updateBook.setBookLastSeq(bookChapter.getChapterSeq());
		bookService.updateBookSeq(updateBook);
		return "redirect:/chapter/draftList?bookId=" + bookChapter.getBookId();
	}

	private String resetContent(String str) {
		str = str.replaceAll("(&nbsp;){1,}", "");
		str = str.replaceAll("(\r\n|\r|\n|\n\r|\t)", "");
		str = str.replaceAll("<br><br>", "</p><p>");
		str = str.replaceAll("<br/><br/>", "</p><p>");
		str = str.replaceAll("<br /><br />", "</p><p>");
		str = str.replaceAll("</p><p></p><p></p><p>", "</p><p>");
		str = str.replaceAll("</p><p></p><p>", "</p><p>");
		str = str.replaceAll("</p><p>", "</p><p>");
		str = str.replaceAll(" ", "");
		str = str.replaceAll("( ){1,}", "");
		str = str.replaceAll("(　){1,}", "");
		// str = str.replaceAll("<br/>", "</p>");
		str = str.replaceAll("<br/>", "</p><p>");
		str = str.replaceAll("<br>", "</p><p>");
		str = str.replaceAll("<p>...</p>", "");
		// str = str.replaceAll("(&emsp;){2,}", "&emsp;&emsp;");
		// str = str.replaceAll("(&nbsp;){2,}", "&emsp;&emsp;");
		str = str.replaceAll("(&emsp;){1,}", "");
		str = str.replaceAll("(&nbsp;){1,}", "");
		// str = str.replaceAll("^<br>", "");
		// str = str.replaceAll("<br>$", "");
		str = str.replaceAll("^</p><p>", "<p>");
		str = str.replaceAll("</p><p>$", "</p>");
		str = str.replaceAll("<p>...</p>", "");
		str = str.replaceAll("<div>", "");
		str = str.replaceAll("</div>", "");
		str = str.replaceAll("<span>", "");
		str = str.replaceAll("</span>", "");
		str = str.replaceAll("(</p>){1,}", "</p>");

		str = str.replaceAll("<(?!p|p|/p|>).*?>", "");// 移除html标签
		str = str.replaceAll("<(pclass).*?>", "<p>");// 移除pclass标签

		str = str.replaceAll("(<p>){1,}", "<p>");
		str = str.replaceAll("(<p></p>){1,}", "");
		return str;
	}

	/**
	 * 验证章节是否排版正确
	 * 
	 * @param str
	 * @return
	 */
	private int valiContent(String str) {
		int count = 0;
		Pattern pattern = Pattern.compile("<p>");
		Matcher matcher = pattern.matcher(str);
		while (matcher.find()) {
			count++;
		}
		return count;
	}

	/**
	 * 只能删除作者所属的草稿箱章节（注意权限验证）
	 * 
	 * @param request
	 * @param bookChapter
	 * @return
	 */
	@RequestMapping("/delete")
	public String chapterDelete(HttpServletRequest request, BookChapter bookChapter, Model model) {
		Author sessionAuthor = this.getSessionAuthor(request);
		String chapterIds = request.getParameter("deleteChapterIds");
		if (StringUtil.isNullOrEmpty(chapterIds)) {
			return this.packStringView(request, "/error", "非法操作！", model);
		}
		String chapterIdArray[] = chapterIds.split(",");
		for (int i = 0; i < chapterIdArray.length; i++) {
			BookChapter findBookChapter = new BookChapter();
			findBookChapter.setBookId(bookChapter.getBookId());
			findBookChapter.setChapterId(Integer.valueOf(chapterIdArray[i]));
			findBookChapter.setChapterStatus(3);
			List<BookChapter> bookChapterList = bookChapterService.findBookChapter(findBookChapter);
			if (bookChapterList.size() == 1) {
				Book findBook = new Book();
				findBook.setAuthorId(sessionAuthor.getAuthorId());
				findBook.setBookId(bookChapterList.get(0).getBookId());
				List<Book> bookList = bookService.findBook(findBook);
				if (bookList.size() == 1) {
					BookChapter deleteBookChapter = new BookChapter();
					deleteBookChapter.setChapterId(Integer.valueOf(chapterIdArray[i]));
					bookChapterService.deleteBookChapter(findBookChapter);
				}
			}
		}

		return "redirect:/chapter/draftList?bookId=" + bookChapter.getBookId();
	}

	/**
	 * 只能发布作者所属的草稿箱章节（注意权限验证）
	 * 
	 * @param request
	 * @param bookChapter
	 * @return
	 */
	@RequestMapping("/publish")
	@Transactional
	public String chapterPublish(HttpServletRequest request, BookChapter bookChapter, Model model) {
		Author sessionAuthor = this.getSessionAuthor(request);
		String chapterIds = request.getParameter("publishChapterIds");
		if (StringUtil.isNullOrEmpty(chapterIds)) {
			return this.packStringView(request, "/error", "非法操作！", model);
		}

		String chapterIdArray[] = chapterIds.split(",");
		for (int i = 0; i < chapterIdArray.length; i++) {
			BookChapter findBookChapter = new BookChapter();
			findBookChapter.setBookId(bookChapter.getBookId());
			findBookChapter.setChapterId(Integer.valueOf(chapterIdArray[i]));
			findBookChapter.setChapterStatus(3);
			List<BookChapter> bookChapterList = bookChapterService.findBookChapter(findBookChapter);
			if (bookChapterList.size() == 1) {
				Book findBook = new Book();
				findBook.setAuthorId(sessionAuthor.getAuthorId());
				findBook.setBookId(bookChapterList.get(0).getBookId());
				List<Book> bookList = bookService.findBook(findBook);
				if (bookList.size() == 1) {
					Book outBook = bookList.get(0);
					boolean isEnablePulish = this.isEnablePublish(outBook.getBookId(), sessionAuthor.getAuthorId());
					if (isEnablePulish) {
						bookChapterService.publishBookChapter(findBookChapter);
						// 书籍发布后更新本月更新天数和字数
						// 更新书籍字数和最后更新时间
						outBook.setBookWords(bookChapterList.get(0).getChapterWords());
						bookService.updateBookWordsAndLatestDate(outBook);
					} else {
						return this.packStringView(request, "/error", "审核中的书籍最多可以发布20章节，上架的书籍不限制，拒绝的书籍不允许发布章节。！",
								model);
					}

				}
			}
		}
		return "redirect:/chapter/publishList?bookId=" + bookChapter.getBookId();
	}

	/**
	 * 验证该章节是否允许发布
	 * 
	 * @param bookId
	 * @param authorId
	 * @return
	 */
	private boolean isEnablePublish(int bookId, int authorId) {
		Book findBook = new Book();
		findBook.setBookId(bookId);
		findBook.setAuthorId(authorId);
		List<Book> bookList = bookService.findBook(findBook);
		if (bookList.size() == 1) {
			Book bk = bookList.get(0);
			// 0默认，1通过，-1拒绝，2审核中
			if (bk.getBookStatus() == 1) {
				return true;
			} else if (bk.getBookStatus() == 2) {
				// 审核中的书籍最多发布20章节
				BookChapter findBookChapter = new BookChapter();
				findBookChapter.setBookId(bk.getBookId());
				findBookChapter.setLimit(50);
				List<BookChapter> bookChapterPublishList = bookChapterService.findBookChapterPublish(findBookChapter);
				if (bookChapterPublishList.size() > 20) {
					return false;
				} else {
					return true;
				}
			} else {
				return false;
			}
		}
		return false;
	}

	@RequestMapping("/edit")
	public ModelAndView chapterEdit(HttpServletRequest request, HttpServletResponse response, BookChapter bookChapter) {
		Author sessionAuthor = this.getSessionAuthor(request);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookId(bookChapter.getBookId());
		List<Book> bookList = bookService.findBook(findBook);
		attrMap.put("bookId", bookChapter.getBookId());
		if (bookList.size() == 1) {
			attrMap.put("book", bookList.get(0));
		}
		List<BookChapter> bookChapterList = bookChapterService.findBookChapterById(bookChapter.getChapterId());
		if (bookChapterList.size() == 1) {
			attrMap.put("bookChapter", bookChapterList.get(0));
			attrMap.put("lastPageNo", this.getLastPageNo(request));
			return this.packModeAndView(request, "/draftEdit", null, attrMap);
		} else {
			return this.packModeAndView(request, "/error", "非法操作！", attrMap);
		}
	}

	@RequestMapping("/update")
	public String chapterUpdate(HttpServletRequest request, BookChapter bookChapter,Model model) {
		Author sessionAuthor = this.getSessionAuthor(request);
		String chapterContent = request.getParameter("content1");
		chapterContent = this.resetContent("<p>" + chapterContent);
		int count = this.valiContent(chapterContent);
		if (count < 3) {
			return this.packStringView(request, "/error", "章节排版存在错误，请注意排版，头文字不用缩进，段落要回车换行。如有问题请点击查看使用帮助或联系QQ客服！",
					model);
		}
		bookChapter.setChapterContent(chapterContent);
		// 如果是付费，则计算价格
		if (bookChapter.getChapterFree() == 2) {
			double chapterAmount = BigDecimalUtil.mul(BigDecimalUtil.div(bookChapter.getChapterWords(), 1000, 2), 0.05);
			chapterAmount = BigDecimalUtil.round(chapterAmount, 2);
			bookChapter.setChapterAmount(chapterAmount);
		}
		bookChapterService.updateBookChapter(bookChapter);
		return "redirect:/chapter/draftList?bookId=" + bookChapter.getBookId() + "&pageNo="
				+ this.getLastPageNo(request);
	}

	@RequestMapping("/editPublish")
	public ModelAndView chapterEditPublish(HttpServletRequest request, HttpServletResponse response,
			BookChapter bookChapter) {
		Author sessionAuthor = this.getSessionAuthor(request);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookId(bookChapter.getBookId());
		List<Book> bookList = bookService.findBook(findBook);
		attrMap.put("bookId", bookChapter.getBookId());
		if (bookList.size() == 1) {
			attrMap.put("book", bookList.get(0));
		}
		List<BookChapter> bookChapterList = bookChapterService.findBookChapterById(bookChapter.getChapterId());
		if (bookChapterList.size() == 1) {
			attrMap.put("bookChapter", bookChapterList.get(0));
			attrMap.put("lastPageNo", this.getLastPageNo(request));
			return this.packModeAndView(request, "/publishEdit", null, attrMap);
		} else {
			return this.packModeAndView(request, "/error", "非法操作！", attrMap);
		}
	}

	@RequestMapping("/updatePublish")
	public String chapterUpdatePublish(HttpServletRequest request, BookChapter bookChapter,Model model) {
		Author sessionAuthor = this.getSessionAuthor(request);
		String chapterContent = request.getParameter("content1");
		chapterContent = this.resetContent("<p>" + chapterContent);
		int count = this.valiContent(chapterContent);
		if (count < 3) {
			return this.packStringView(request, "/error", "章节排版存在错误，请注意排版，头文字不用缩进，段落要回车换行。如有问题请点击查看使用帮助或联系QQ客服！",
					model);
		}
		bookChapter.setChapterContent(chapterContent);
		// 如果是付费，则计算价格
		if (bookChapter.getChapterFree() == 2) {
			double chapterAmount = BigDecimalUtil.mul(BigDecimalUtil.div(bookChapter.getChapterWords(), 1000, 2), 0.05);
			chapterAmount = BigDecimalUtil.round(chapterAmount, 2);
			bookChapter.setChapterAmount(chapterAmount);
		}
		bookChapterService.updateBookChapter(bookChapter);
		return "redirect:/chapter/publishList?bookId=" + bookChapter.getBookId() + "&pageNo="
				+ this.getLastPageNo(request);
	}

	@RequestMapping("/review")
	public ModelAndView chapterReview(HttpServletRequest request, HttpServletResponse response,
			BookChapter bookChapter) {
		Author sessionAuthor = this.getSessionAuthor(request);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookId(bookChapter.getBookId());
		List<Book> bookList = bookService.findBook(findBook);
		attrMap.put("bookId", bookChapter.getBookId());
		if (bookList.size() == 1) {
			attrMap.put("book", bookList.get(0));
		}
		List<BookChapter> bookChapterList = bookChapterService.findBookChapterById(bookChapter.getChapterId());
		if (bookChapterList.size() == 1) {
			attrMap.put("bookChapter", bookChapterList.get(0));
			return this.packModeAndView(request, "/chapterReview", null, attrMap);
		} else {
			return this.packModeAndView(request, "/error", "非法操作！", attrMap);
		}
	}

	@RequestMapping("/help")
	public ModelAndView chapterHelp(HttpServletRequest request, HttpServletResponse response, BookChapter bookChapter) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		return this.packModeAndView(request, "/help", null, attrMap);

	}
}
